package ai.yale.web;

import ai.yale.bean.Message;
import ai.yale.config.ChatHandler;
import ai.yale.dao.MessageRepository;
import ai.yale.util.RespMessage;
import ai.yale.vo.MessageVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;

import java.util.UUID;

/**
 * Created by asus on 2017/8/17.
 */

@RestController
@CrossOrigin
@RequestMapping("/message")
public class SocketController {

    @Autowired
    ChatHandler handler;

    @Autowired
    MessageRepository messageRepository;

    @RequestMapping("/send")
    public RespMessage sendMessage(MessageVo vo) {

        // 存入数据库
        Message message = new Message();
        BeanUtils.copyProperties(vo, message);
        message.setReadFlag(false);
        message.setSendFlag(false);
        message.setId(UUID.randomUUID().toString());
        messageRepository.save(message);

        handler.sendMessageToUser(vo.getFromUser(), new TextMessage(JSON.toJSONString(vo)));

        boolean hasSend = handler.sendMessageToUser(vo.getToUser(), new TextMessage(JSON.toJSONString(vo)));
        if (hasSend) {
            message.setSendFlag(true);
            messageRepository.save(message);
            return RespMessage.success("已发送");
        }
        System.out.println(hasSend);
        return RespMessage.success("用户不在线");
    }

    @RequestMapping("/list")
    public RespMessage list(String userId) {
        return RespMessage.success();
    }

    @RequestMapping("/read")
    public RespMessage read(String messageId) {
        return RespMessage.success();
    }
}
